package Tier1;

import java.util.Properties;
import org.omg.CORBA.ORB;
import org.omg.CosNaming.NamingContextExt;
import org.omg.CosNaming.NamingContextExtHelper;
import org.omg.PortableServer.POA;
import org.omg.PortableServer.POAHelper;

import Shared._Config;

/**
 * Hérite de application Client et implémente le protocole Corba.
 *
 */
public class UserIIOP {
    
    public class CallbackImpl extends Tier2.ORB_PartyManager.CallbackPOA {
	private User.Callback _proxy = null;
	public void setProxy(User.Callback proxy) { _proxy = proxy; }
	
	@Override
	public void callback(String msg) {
	    System.out.print("- ");
	    _proxy.say(msg);
	}
    }

    public static void main(String args[]) throws Exception {

	User user = new User();
	
	// Création de la couche ORB

	Properties props = new Properties();
	props.put("org.omg.CORBA.ORBInitialPort", _Config.ORB_port);
	props.put("org.omg.CORBA.ORBInitialHost", _Config.ORB_host);
	ORB orb = ORB.init((String[]) null, props);

	// Creation du callback client
	
	Tier1.UserIIOP.CallbackImpl callbackImpl = new Tier1.UserIIOP().new CallbackImpl();
	User.Callback proxy = user.new Callback();
	callbackImpl.setProxy(proxy);
	
	POA rootPOA = POAHelper.narrow(orb.resolve_initial_references("RootPOA"));
	rootPOA.activate_object(callbackImpl);
	rootPOA.the_POAManager().activate();
	Tier2.ORB_PartyManager.Callback callback = Tier2.ORB_PartyManager.CallbackHelper.narrow(rootPOA.servant_to_reference(callbackImpl));
	
 	// Recherche du service de nommage (annuaire d'objet)
	
 	org.omg.CORBA.Object serviceNommageRef = orb.resolve_initial_references(_Config.ORB_services);
 	NamingContextExt serviceNommage = NamingContextExtHelper.narrow(serviceNommageRef);

 	// Recherche du service <Party Manager> auprès du service de nommage + ajout callback
 	
 	org.omg.CORBA.Object reference  = serviceNommage.resolve_str(_Config.party_manager);
 	Tier2.ORB_PartyManager.PartyManager service = Tier2.ORB_PartyManager.PartyManagerHelper.narrow(reference);
 	service.callback(user.hashCode() + "", callback);
 	
 	// Rend la main à <User>
 	System.out.println("("+user.hashCode()+")"+callback.hashCode());
 	user.init(null, service, proxy).run();
     }
}
